const mongoose = require("mongoose");

mongoose.connect("mongodb://127.0.0.1:27017/bilibili");

mongoose.set("strictQuery", true);
mongoose.connection.once("open", () => {
  console.log("连接成功");
  // 创建文档的结构对象
  // 设置集合中文档的属性以及属性值的类型
  let BookSchema = new mongoose.Schema({
    name: String,
    author: String,
    price: Number,
  });

  // 创建模型对象 对文档操作的封装对象
  let BookModel = mongoose.model("books", BookSchema);

  // 新增
  BookModel.create(
    {
      name: "西游记",
      author: "吴承恩",
      price: 19.9,
    },
    (err, data) => {
      if (err) {
        return console.log(err);
      }
      console.log(data);
      // 关闭数据库连接(项目运行中不会添加)
      mongoose.disconnect();
    }
  );
});

mongoose.connection.on("error", () => {
  console.log("连接失败");
});

mongoose.connection.on("close", () => {
  console.log("连接关闭");
});
